import React from 'react';
import { connect } from 'umi';
import { DatePicker, Spin, Select } from 'antd';
import moment from 'moment';

import TMainBasePage from '@/base/TMainBasePage';
import { CaretDownOutlined } from '#/utils/antdIcons';
import { AlertResult, HttpCode } from '#/utils/contacts.js';

import { getStartAndEndDate } from '@/pages/BusinessAnalysis/helper';
import { getOperationDate } from '@/pages/BusinessAnalysis/service';
import CentreModal from '@/pages/BusinessAnalysis/components/CentreModal';
import { flatArr } from '@/pages/BusinessAnalysis/Operate/helper';
import Transaction from '@/pages/BusinessAnalysis/Transaction';
import { getDictionaryValue } from '@/services/common';
import { getSourceSelectData, getSourceSelectModalData } from '@/services/businessAnalysis';

import { getDisabledDate, powerType } from './helper';
import styles from './index.less';

const MockExtra = {
  week: { title: '周报', format: '第wo' },
  month: { title: '月报', format: 'MM月' },
  year: { title: '年报', format: 'YYYY年' },
};

const DEFAULT_DATE = moment().add(-1, 'd');

export const { Provider, Consumer } = React.createContext(null);
@connect(({ global }) => ({
  menuCode: global.configure.menuCode,
}))
export default class ElectricityAnalysis extends TMainBasePage {
  constructor(props) {
    super(props);
    this.state.spinLoading = false; //页面导航菜单
    this.state.chooseDate = DEFAULT_DATE;
    this.state.type = 'month';
    this.state.powerTypeValue = '全部';
    this.state.pickerProps = { picker: 'month', format: MockExtra['month'].format };
    this.state.resultstationList = [];
    this.state.expandList = [];
    this.state.centerData = [];
    this.state.sourceSelectData = [powerType];
    this.state.dateObj = getStartAndEndDate(DEFAULT_DATE, 'month');
    this.state.dateBody = {};
    this.state.updateData = {};
  }

  async componentDidMount() {
    this._openCenterData();
    this._getSourceSelectData();
    this.fetchUpdateDate();
    this.fetchData();
  }

  fetchData = async () => {
    let res = await getDictionaryValue('BPFT');
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const { dictionaryValueBodies } = res;
      const updateData = {};
      dictionaryValueBodies.map((item) => {
        let [user, method, updateDate] = item.description.split('，');
        updateData[item.value] = { user, method, updateDate };
      });
      this.setState({ updateData });
    }
  };

  fetchUpdateDate = async () => {
    let res = await getOperationDate();
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const { dateBody } = res;
      this.setState({ dateBody });
    }
  };

  getData() {}

  // 运营下拉框
  _getSourceSelectData = async () => {
    let res = await getSourceSelectData();
    if (res && res.statusCode === HttpCode.SUCCESS) {
      let userTypeLists = res.userTypeList || [];
      userTypeLists = userTypeLists
        .filter((n) => n.code === '0')
        .map((n) => n.children)
        .flat();
      this.setState({
        sourceSelectData: [...powerType, ...userTypeLists],
      });
    }
  };

  _onGetParams = () => {
    const { dateObj, resultstationList, centerData, type } = this.state;
    const { startDate, endDate } = dateObj;
    let projectIds = resultstationList.length ? resultstationList : flatArr(centerData);
    return {
      startDate,
      endDate,
      projectIds: projectIds.map((n) => n.deptNum),
      type: type || '',
    };
  };

  _openCenterData = async () => {
    //中心弹框数据
    let res = await getSourceSelectModalData({
      assetManagementType: null,
      powerGenerationType: null,
    });

    if (res && res.statusCode === HttpCode.SUCCESS) {
      this.setState(
        {
          centerData: res.userTypeList,
        },
        () => {
          this.getData();
        },
      );
    }
  };

  _onHandleType = (key) => {
    // const configPage = getPageConent(this.state.pageMenuList, key);
    this.setState(
      {
        type: key,
        dateObj: getStartAndEndDate(DEFAULT_DATE, key),
        chooseDate: DEFAULT_DATE,
        // pageConfig: configPage,
        pickerProps: {
          picker: key,
          format: MockExtra[key].format,
        },
      },
      () => {
        this.getData();
      },
    );
  };

  _disabledDate(current) {
    if (current) {
      return (
        current < moment('2019-12-31').subtract(1, 'days') ||
        current > getDisabledDate(this.state.type)
      );
    }
    return false;
  }

  handleChange = (date) => {
    const { type } = this.state;
    const data = getStartAndEndDate(date, type);
    this.setState(
      {
        chooseDate: date,
        dateObj: data,
      },
      () => {
        this.getData();
      },
    );
  };
  onPickerWithType(type, chooseDate, pickerProps) {
    const pops = {
      bordered: false,
      value: chooseDate,
      defaultValue: moment(),
      allowClear: false,
      disabledDate: this._disabledDate.bind(this),
      onChange: this.handleChange.bind(this),
      inputReadOnly: true,
    };
    return <DatePicker {...pops} {...pickerProps} mode={type} />;
  }

  //头部右侧日期切换 周报 月报 年报
  HeaderExtraRender = () => {
    const { chooseDate, type, pickerProps } = this.state;
    return (
      <div className={styles.headerExtra}>
        <div className={styles.left}>
          {Object.entries(MockExtra).map(([key, item]) => (
            <span
              key={key}
              value={key}
              className={type === key ? styles.active : undefined}
              onClick={this._onHandleType.bind(this, key)}
            >
              {item.title}
            </span>
          ))}
        </div>
        <div className={styles.right}>{this.onPickerWithType(type, chooseDate, pickerProps)}</div>
      </div>
    );
  };
  _openCenter = async () => {
    const { resultstationList, expandList, centerData } = this.state;
    let echoArr = resultstationList.length > 0 ? resultstationList : [];
    let result = await CentreModal.show(centerData, expandList, echoArr, undefined, true);
    if (result.index === AlertResult.SUCCESS) {
      this.setState(
        {
          resultstationList: result.stationList,
          expandList: result.expandList,
        },
        () => {
          this.getData();
        },
      );
    }
  };

  HeaderType = () => {
    const { powerTypeValue, resultstationList, sourceSelectData } = this.state;
    return (
      <div className={styles.headerType}>
        <span>中心：</span>
        <span onClick={this._openCenter} style={{ cursor: 'pointer' }}>
          {resultstationList.length ? `已选择${resultstationList.length}项` : '全部'}

          <CaretDownOutlined
            style={{ fontSize: '12px', color: '#9DA0A6', marginLeft: 10, marginRight: 50 }}
          />
        </span>
        <span>发电类型：</span>
        <Select
          dropdownMatchSelectWidth={false}
          bordered={false}
          onChange={(val) =>
            this.setState({ powerTypeValue: val }, () => {
              this.getData();
            })
          }
          className={['sele', styles.dq_datepicker]}
          value={powerTypeValue}
          suffixIcon={<CaretDownOutlined style={{ fontSize: '12px', color: '#9DA0A6' }} />}
        >
          {sourceSelectData.map((item, index) => (
            <Select.Option key={index} value={item?.code}>
              {item?.name}
            </Select.Option>
          ))}
        </Select>
      </div>
    );
  };

  render() {
    const { spinLoading, dateObj, dateBody, updateData } = this.state;
    return (
      <Spin spinning={spinLoading}>
        <div className={styles.businessOperationAnalysis}>
          {/*{this.HeaderType()}*/}
          <div className={styles.contentScroll}>
            {this.HeaderExtraRender()}
            <div className={styles.electricityAnalysisContent}>
              <Transaction
                dateObj={dateObj}
                title={'交易'}
                type={'Transaction'}
                code={'Transaction'}
                revenueAnalysis={true}
                revenueAnalysisData={{ dateBody, updateData }}
              />
            </div>
          </div>
        </div>
      </Spin>
    );
  }
}
